package com.blb.service;

import java.io.IOException;
import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.blb.entity.Role;
import com.blb.entity.RoleExample;
import com.blb.entity.RoleExample.Criteria;
import com.blb.mapper.RoleMapper;
import com.blb.utils.LayuiPage;
import com.blb.utils.MybatisUtils;
import com.mysql.jdbc.StringUtils;

public class RoleService {

	private SqlSession  session;
	
	
	/**
	 * 分页
	 * @param page
	 * @param limit
	 * @param rolename
	 * @return
	 * @throws IOException
	 */
	public LayuiPage page(int page,int limit,String rolename) throws IOException{
		session = MybatisUtils.getSession();
		RoleMapper roleMapper = session.getMapper(RoleMapper.class);
		List<Role> list = roleMapper.page(page, limit, rolename);
		
		RoleExample roleExample = new RoleExample();
		Criteria criteria = roleExample.createCriteria();
		if(StringUtils.isNullOrEmpty(rolename)){
			criteria.andRolenameLike("%"+ rolename + "%");
		}
		
		int count = (int) roleMapper.countByExample(roleExample);
		
		LayuiPage layuiPage = new LayuiPage();
		layuiPage.setCount(count);
		layuiPage.setData(list);
		
		session.close();
		return layuiPage;
	}
	
	/**
	 * 判断角色是否存在
	 * @param rolename
	 * @return
	 * @throws IOException
	 */
	public List<Role> isExist(String rolename) throws IOException{
		session = MybatisUtils.getSession();
		RoleMapper roleMapper = session.getMapper(RoleMapper.class);
		RoleExample roleExample = new RoleExample();
		Criteria criteria = roleExample.createCriteria();
		criteria.andRolenameEqualTo(rolename);
		
		List<Role> list = roleMapper.selectByExample(roleExample);
		return list;
	}
	
	/**
	 * 添加角色
	 * @param role
	 * @throws IOException
	 */
	public void add(Role role) throws IOException{
		session = MybatisUtils.getSession();
		RoleMapper roleMapper = session.getMapper(RoleMapper.class);
		roleMapper.insertSelective(role);
		
		session.commit();
		session.close();
	}
	
	/**
	 * 修改角色
	 * @param role
	 * @throws IOException
	 */
	public void update(Role role) throws IOException{
		session = MybatisUtils.getSession();
		RoleMapper roleMapper = session.getMapper(RoleMapper.class);
		
		RoleExample roleExample = new RoleExample();
		Criteria criteria = roleExample.createCriteria();
		criteria.andIdEqualTo(role.getId());
		
		roleMapper.updateByExample(role, roleExample);
		
		session.commit();
		session.close();
	}
	
	
	/**
	 * 删除角色
	 * @param roleIds
	 * @throws IOException
	 */
	public void delete(List<String> roleIds) throws IOException{
		session = MybatisUtils.getSession();
		RoleMapper roleMapper = session.getMapper(RoleMapper.class);
		
		RoleExample roleExample = new RoleExample();
		Criteria criteria = roleExample.createCriteria();
		criteria.andIdIn(roleIds);
		
		roleMapper.deleteByExample(roleExample);
		
		session.commit();
		session.close();
	}
}
